# -*- coding: utf-8 -*-
#
# Copyright (C) 2011  Benjamin Heil
#
# This file is part of Feedmail.
#
# Feedmail is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import hashlib
import feedparser

from django.conf import settings
from django.utils.encoding import smart_unicode
from django.utils.html import escape
from django.template import Context
from django.template.loader import get_template
from html2text import html2text

def contains(a, b):
    return a.find(b) != -1

def _is_html(t):
    return type(t) is type(())

def getFeedName(url):
    feed = feedparser.parse(url, agent=settings.FEEDPARSER_USER_AGENT)
    try:
        name = feed.feed.title.encode('utf-8')
        return name
    except:
        return u"noname"

def getEntryName(feed, entry):
    name = feed.name
    if 'name' in entry.get('author_detail', []): # normally {} but py2.1
        if entry.author_detail.name:
            if name:
                name += ": "
            try:
                name += entry.author_detail.name
            except UnicodeDecodeError:
                name += unicode(entry.author_detail.name, 'utf-8')
    return name

def getEntryContent(entry):
    conts = entry.get('content', [])
    if entry.get('summary_detail', {}):
        conts += [entry.summary_detail]
    try:
        if conts:
            for c in conts:
                if contains(c.type, 'html'):
                    return ('HTML', c.value)
            for c in conts:
                if c.type == 'text/plain':
                    return c.value
            return conts[0].value
    except AttributeError:
        # Bei manchen Feeds wird nur ein leerer Content geliefert
        # 'content': [{'value': u''}], Beispiel http://sourceforge.net/api/file/index/project-id/170561/mtime/desc/limit/20/rss
        pass
    return ''

def getEntryFingerprint_MD5(entry, fingerprint=None):
    if not fingerprint:
        fingerprint = getEntryFingerprint(entry)
    m = hashlib.md5()
    m.update(fingerprint.encode('utf-8'))
    return m.hexdigest()
    
def getEntryFingerprint(entry):
    if 'id' in entry and entry.id:
        return entry.id

    content = getEntryContent(entry)
    if content and content != "\n":
        hash = hashlib.md5()
        hash.update(smart_unicode(content))
        return hash.hexdigest()
    if 'link' in entry:
        return entry.link
    if 'title' in entry:
        hash = hashlib.md5()
        hash.update(smart_unicode(entry.title))
        return hash.hexdigest()
    raise ValueError("can't find ID in getID")

def getEntryTitle(entry):
    if 'title_detail' in entry and entry.title_detail:
        title = entry.title_detail.value
        if contains(entry.title_detail.type, 'html'):
            title = html2text(title)
    else:
        title = getEntryContent(entry)[:40]
        if _is_html(title):
            title = html2text(title[1])
    title = _get_stripped(title.replace("\n", " "))
    return title

def getEntryBody(entry, title):
    link = entry.get('link', '')

    entry_content = getEntryContent(entry)
    if _is_html(entry_content):
        body = _get_stripped(entry_content[1])
    else:
        body = _get_stripped(entry_content)

    enclosure_list = ''
    if hasattr(entry, 'enclosures'):
        for enclosure in entry.enclosures:
            if (hasattr(enclosure, 'url') and enclosure.url != ""):
                enc_url = smart_unicode(enclosure.url)
                enclosure_list += (u'<br/>Anhang: <a href="%s">%s</a>\n' % (enc_url, enc_url))
            if (hasattr(enclosure, 'src') and enclosure.src != ""):
                enc_src = smart_unicode(enclosure.src)
                enclosure_list += (u'<br/>Anhang: <a href="%s">%s</a><br/><img src="%s"\n' % (enc_src, enc_src, enc_src))

    mail_body = get_template('mail/entry.html')
    mail_body_data = Context({
        'css': settings.MAIL_STYLE_SHEET,
        'link': link,
        'title': title,
        'body': body,
        'enclosures': enclosure_list,
        'site_url': settings.ROOT_URL,
        'site_title': settings.SITE_TITLE
    })
    rendered_body = mail_body.render(mail_body_data)
    return rendered_body

def _get_stripped(s):
    if s:
        return s.strip()
    else:
        return s

def getEntryTags(entry):
    tagline = u''
    if 'tags' in entry:
        tags = entry.get('tags', [])
        taglist = [smart_unicode(_get_stripped(tag['term'])) for tag in tags]
        if taglist:
            tagline = u','.join(taglist)
            if tagline.find("\n") > 0:
                # Remove "\n" if this is embedded by the original feed and not caugth by strip()
                # This is a problem with feeds from web.de sometimes
                tagline = tagline.replace("\n", '')
    return tagline
